from selenium import webdriver  # 驱动浏览器
from selenium.webdriver.common.by import By  # 定位
from selenium.webdriver import ActionChains  # 鼠标悬停的包
import time

# 打开浏览器
c = webdriver.Chrome()   # 打开谷歌浏览器
c.maximize_window()  # 最大化窗口
# 打开网址
c.get("http://192.168.0.125:9009/")
# 滚动条 下拉
js = "window.scrollTo(0,1000);"
c.execute_script(js)  # 执行js语句
# 通过文本链接定位到登录按钮
login_button = c.find_element(By.LINK_TEXT, '登录')
# 点击登录按钮
login_button.click()

# 通过css选择器定位到用户输入框
username_ele = c.find_element(By.CSS_SELECTOR, '[id="user_login"]')
# 通过css选择器定位到密码输入框
pwd_ele = c.find_element(By.CSS_SELECTOR, '[name="pwd"]')
# 通过css选择器定位到登录按钮
login_ele = c.find_element(By.CSS_SELECTOR, '[name="wp-submit"]')

# 输入用户名和密码
username_ele.send_keys('admin')
time.sleep(1)
pwd_ele.send_keys('admin123')
time.sleep(1)
# 点击登录按钮
login_ele.click()

# 定位到需要悬停的元素
post_link = c.find_element(By.CSS_SELECTOR, '[id="menu-posts"] [class="wp-menu-name"]')
# ActionChains(浏览器).move_to_element(移动到哪个元素).perform()
ActionChains(c).move_to_element(post_link).perform()
time.sleep(1)

write_ele = c.find_element(By.LINK_TEXT, '写文章')
write_ele.click()

# 输入标题
write_title = c.find_element(By.CSS_SELECTOR, '[name="post_title"]')
write_title.send_keys('1232334')
time.sleep(1)

# 切换表单
# 1.先定位到表单所处的frame 或者 iframe 标签
frame_ele = c.find_element(By.CSS_SELECTOR, '[id="content_ifr"]')
# 2.切换
c.switch_to.frame(frame_ele)
time.sleep(1)

# 输入正文
content_ele = c.find_element(By.CSS_SELECTOR, '[id="tinymce"]')
content_ele.send_keys('werwretrgtdgc')
time.sleep(1)

# 跳出表单
c.switch_to.default_content()

# 点击发布按钮
publish_button = c.find_element(By.CSS_SELECTOR, '[name="publish"]')
publish_button.click()
time.sleep(5)

c.quit()